/*
 * @Author: xiangxiaojun
 * @Date: 2022-03-16 10:02:01
 * @Descripttion:
 */
import { useState, useEffect } from 'react';
import _ from 'lodash';
import { Row, Col, message } from 'antd';
import { observer } from '@formily/react';
import { InbizIcon, webDataSourceClick } from '@inbiz/utils';
import { useInbizRouter } from '@inbiz/hooks';
import BizHeader from '@inbiz/basic/BizHeader';
import BizBody from '@inbiz/basic/BizBody';
import { TextWidget, getMessage } from '@inbiz/react';
import './style.less';
const defaultClass = 'inbiz-nav-view'; // 默认样式
const defaultBG = 'rgba(255,255,255,1)'; // 默认背景

// 根据icon图标位置，icon元素映射样式表
const iconCls = {
  left: `${defaultClass}-icon-left`,
  bottom: `${defaultClass}-icon-bottom`,
  right: `${defaultClass}-icon-right`,
  top: `${defaultClass}-icon-top`,
};

// 根据icon图标位置 父级元素映射样式表
const parentCls = {
  none: `${defaultClass}-item-none`,
  top: `${defaultClass}-item-top`,
  left: `${defaultClass}-item-left`,
  right: `${defaultClass}-item-right`,
  bottom: `${defaultClass}-item-bottom`,
};

export interface NavigationProps {
  /** 唯一标识 */
  id?: string;
  /** 标题 */
  title?: {
    status?: boolean;
    value?: string;
  };
  /** 标题图标 */
  icon?: {
    size?: number;
    color?: string;
    type?: string;
  };
  /** 显示规则 */
  showType: 'grid' | 'flex';
  /** 单元格宽度 */
  itemWidth: number;
  /** 列数 */
  rowCount?: number;
  /** 导航List */
  navList?: [
    {
      id: string;
      /** 导航文案 */
      title?: string;
      /** 导航图标 */
      icon?: {
        type?: string;
        color?: string;
        size?: number;
      };
      /** 导航图标大小 */
      iconSize?: number;
      /** 图标背景 */
      iconColor?: string;
      /** 导航背景 */
      blockBackgroundColor?: string;
      /** 导航边框 */
      border?: string;
      /** 导航边框宽度 */
      borderWidth?: number;
      /** 导航边框颜色 */
      borderColor?: string;
      /** 是否展示导航阴影 */
      borderShadow?: boolean;
      /** 是否展示导航标题 */
      titleColor?: string;
      /** 是否展示导航 */
      hide?: boolean;
      parameter: string;
      /** 描述 */
      describe: string;
      [key: string]: any
    },
  ];
  /** 横向间距 默认5px eg: 5*/
  horizontalGutter: number;
  /** 纵向间距 默认5px eg: 5*/
  verticalGutter?: number;
  /** 单元格高度 默认60px eg: 60 or '60px'*/
  colHeight?: number | string;
  /** 单个导航图标位置 上下左右：'top', 'bottom', 'left','right'; 不展示：''  */
  position?: string;
  /** 拓展样式 */
  className?: string;
  /** 导航高度 默认auto eg: 140 or '140px' */
  height?: number | string;
  /** 标题字体大小 */
  titleFontSize?: number;
  /** 标题背景色 */
  titleBackground?: string;
  /** 标题文本颜色 */
  titleFontColor?: string;
  /** 名称字号 */
  fontSize: number;
  /** 名称字色 */
  titleColor: string;
  /** 名称字号 */
  descFontSize: number;
  /** 名称字色 */
  descColor: string;
  /** 文字对齐 */
  textAlign: 'left' | 'right' | 'center';
  /** 卡片圆角 */
  radius: number;
  /** 卡片背景 */
  cardBackground?: any;
  /** 卡片阴影 */
  cardBoxshadow?: string
  /** 卡片边框 */
  cardBorder?: any;
  /** 卡片背景 */
  hoverBackground?: any;
  /** 卡片阴影 */
  hoverBoxshadow?: string
  emit?: (name: string, val?: any) => void;
}

const Navigation = observer((props: NavigationProps) => {
  const {
    navList,
    horizontalGutter,
    verticalGutter,
    colHeight,
    position,
    height,
    rowCount,
    titleColor,
    fontSize,
    descColor,
    descFontSize,
    cardBackground,
    hoverBackground,
    radius,
    textAlign,
    cardBorder,
    cardBoxshadow,
    hoverBoxshadow,
  } = props;
  const boxHeight = height || 'auto';

  const history = useInbizRouter();

  const [hoverId, $hoverId] = useState<string>('')

  // 导航跳转
  const onJump = (values: any) => {
    props.emit?.('onclick', values);
    if (values.externalAddress && values.linkAddress) {
      let link = values.linkAddress || ''
      let parameter = values.parameter?.replace('?', '');
      let isHash = link?.indexOf('#')
      let isSearch = isHash > -1 ? link.substring(isHash + 1).indexOf('?') > -1 : link.indexOf('?') > -1
      if (parameter) {
        if (isSearch) {
          link = link + '&' + parameter
        } else {
          link = link + '?' + parameter
        }
      }
      window.open(link);
    } else if (values.page) {
      webDataSourceClick(history, values);
      // const baseUrl = window.location.href;
      // const router = values.page.split(',')[0];
      // const index = baseUrl.lastIndexOf('/');
      // window.location.href = `${baseUrl.substring(0, index + 1)}${router}`;
    } else {
      return message.warn(getMessage('navigation.noPage'));
    }
  };

  // 单元格宽度
  const renderColSty = () => {
    return rowCount
      ? {
        display: 'block',
        flex: props.showType === 'flex' ? 1 : `0 0 ${100 / rowCount}%`,
        maxWidth: props.showType === 'flex' ? props.itemWidth + horizontalGutter : `${100 / rowCount}%`,
        minWidth: props.showType === 'flex' ? props.itemWidth + horizontalGutter : `${100 / rowCount}%`,
      }
      : undefined;
  };

  const getCols = () => {
    // 导航公共样式
    const commonStyle = {
      minHeight: colHeight,
      maxHeight: colHeight,
      borderRadius: radius,
      ...cardBorder
    }

    // 导航公共变化样式
    const rowNav = {
      ...cardBackground,
      boxShadow: cardBoxshadow,
    }

    const { backgroundImage, backgroundPosition, backgroundSize, backgroundRepeat, ..._rowNav } = rowNav
    // 导航公共hover样式
    const rowNavHover = {
      ..._rowNav,
      ...hoverBackground,
      boxShadow: hoverBoxshadow ?? cardBoxshadow
    }

    let colNav: any = {};
    let colNavHover: any = {};
    let viewDescColor = descColor;
    let viewDescFontSize = descFontSize ?? 14;
    let viewTitleColor = titleColor;
    let viewTitleFontSize = fontSize ?? 16;

    if (navList && navList.length) {
      const arr: any[] = [];
      navList.forEach((item, index) => {
        // 升级兼容阴影样式-1H
        const borderShadow = item.borderShadow ? `${defaultClass}-item-shadow` : '';
        colNav = {
          // 升级兼容-3H
          backgroundColor: item?.blockBackgroundColor,
          borderColor: item?.borderColor,
          // @ts-ignore 兼容升级borderWidth为''
          borderWidth: item?.borderWidth === '' ? 0 : item?.borderWidth,
          borderStyle: item?.borderColor ? 'solid' : '',
          ...commonStyle,
          ...rowNav,
        }
        colNavHover = {
          // 升级兼容-3H
          backgroundColor: 'rgba(245,245,245,1)',
          borderColor: item?.borderColor,
          // @ts-ignore 兼容升级borderWidth为''
          borderWidth: item?.borderWidth === '' ? 0 : item?.borderWidth,
          borderStyle: item?.borderColor ? 'solid' : '',
          ...commonStyle,
          ...rowNavHover,
        }
        viewTitleColor = titleColor ?? item?.titleColor ?? 'rgba(0,0,0,1)';

        // 如果不随公共样式
        if (item.cardStyle) {
          // 该项组合样式
          if (true) {
            const { backgroundImage, backgroundPosition, backgroundSize, backgroundRepeat, borderColor, borderWidth, borderStyle, ..._colNav } = colNav
            colNav = {
              ..._colNav,
              ...item.cardBackground,
              ...item.cardBorder,
              // @ts-ignore
              boxShadow: item.cardBoxshadow ?? rowNav.boxShadow ?? colNav?.boxShadow ?? '',
            }
          }
          // 该项hover样式
          if (true) {
            const { backgroundImage, backgroundPosition, backgroundSize, backgroundRepeat, borderColor, borderWidth, borderStyle, ..._colNavHover } = colNavHover
            colNavHover = {
              ..._colNavHover,
              ...item.hoverBackground || item.cardBackground,
              ...item.cardBorder,
              // @ts-ignore
              boxShadow: item.hoverBoxshadow ?? rowNav.hoverBoxshadow ?? colNavHover?.boxShadow ?? '',
            }
          }

          viewDescColor = item.describeColor ?? descColor ?? 'rgba(235,235,235,1)';
          viewDescFontSize = item.describeFontSize ?? descFontSize ?? 14;
          viewTitleColor = item.nameColor ?? viewTitleColor ?? 'rgba(0,0,0,1)';
          viewTitleFontSize = item.nameFontSize ?? fontSize ?? 16;
        }

        if (!item.hide) {
          arr.push(
            <Col key={index} style={renderColSty()}>
              <div
                onClick={() => onJump(item)}
                onMouseEnter={() => $hoverId(item.id)}
                onMouseLeave={() => $hoverId('')}
                className={`${defaultClass}-item ${defaultClass}-item-h ${borderShadow}`}
                style={hoverId === item.id ? colNavHover : colNav}
              >
                <span
                  // @ts-ignore
                  className={`${position ? parentCls[position] : parentCls['none']} spanContainer`}
                >
                  {position && position !== 'bottom' && _.get(item, 'icon.type') ? (
                    // @ts-ignore
                    <div className={iconCls[position]} style={{ textAlign: 'center', marginLeft: position === 'right' ? 10 : 0, marginRight: position === 'left' ? 10 : 0 }}>
                      <InbizIcon
                        type={_.get(item, 'icon.type')}
                        style={{
                          fontSize: _.get(item, 'icon.size'),
                          color: _.get(item, 'icon.color'),
                        }}
                      />
                    </div>
                  ) : null}
                  <div
                    style={{
                      flex: 1,
                      display: 'flex',
                      flexDirection: 'column',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {/* 标题 */}
                    <span
                      title={getMessage(item.title)}
                      style={{
                        color: viewTitleColor,
                        fontSize: viewTitleFontSize,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        textAlign: textAlign || 'center',
                      }}
                    >
                      <TextWidget>{item.title}</TextWidget>
                    </span>
                    {/* 描述 */}
                    <span
                      title={getMessage(item.describe)}
                      style={{
                        color: viewDescColor,
                        fontSize: viewDescFontSize,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        textAlign: textAlign || 'left',
                      }}
                    >
                      <TextWidget>{item.describe}</TextWidget>
                    </span>
                  </div>
                  {position == 'bottom' && _.get(item, 'icon.type') ? (
                    <div className={iconCls[position]} style={{ textAlign: 'center', marginTop: 5 }}>
                      <InbizIcon
                        type={_.get(item, 'icon.type')}
                        style={{
                          fontSize: _.get(item, 'icon.size'),
                          color: _.get(item, 'icon.color'),
                        }}
                      />
                    </div>
                  ) : null}
                </span>
              </div>
            </Col>,
          );
        }
      });
      return arr;
    }
  };

  return (
    <div className={`${defaultClass}`} style={{ height: boxHeight }}>
      <BizHeader {...props} />
      <BizBody {...props}>
        <div
          className={`${defaultClass}-item-box`}
          style={{ margin: `0 0 0 -${props.horizontalGutter / 2}px` }}
        >
          <Row gutter={[horizontalGutter || 0, verticalGutter || 0]}>{getCols()}</Row>
        </div>
      </BizBody>
    </div>
  );
});

export default Navigation;
